<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Goodssale;
use App\Model\Goods;
use Illuminate\Support\Facades\Redis;

/**
 * 前台商品促销相关的Api
 * @author [cjinhui] <[514384598@qq.com]>
 */
class HomeGoodsSaleApi extends Controller
{
    /**
     * 查询促销商品[每次查询四个]
     * @return   [返回一个二维数组]
     */
    public function getGoodsSale()
    {

        //促销商品集合的键名
        $setGoodsKey = 'goods_sale_set_data';

        //如果Redis中没有数据就查数据库
        if (empty(Redis::sMembers($setGoodsKey))) {

        	$res = Goodssale::select('id', 'goods_id', 'goods_name', 'start_time', 'end_time', 'price', 'promate_price', 'promate_num', 'status')->where('status', 0)->get()->toArray();
        	
        	foreach ($res as $k => $val) {

        		$good = Goods::select('goods_pic')->where('id', $val['goods_id'])->first();
        		$val['goods_pic'] = $good->goods_pic;

        		//写入Redis
        		//定义一个哈希键
        		$hashGoodsKey = 'goods_sale_hash_data:'.$val['goods_id'];
        		Redis::sAdd($setGoodsKey, $hashGoodsKey);
        		Redis::hMSet($hashGoodsKey, $val);

        	}

        }


        $GoodsSaleHash = Redis::sRandMember($setGoodsKey, 4);

        foreach ($GoodsSaleHash as $k => $v) {

        	$sales[] = Redis::hGetAll($v);
        }

        if (!empty($sales)) {
            
            return $sales;
        }

    }
}
